from fastapi import APIRouter, Body, Depends, Request, HTTPException
from fastapi.responses import StreamingResponse, JSONResponse
from sqlalchemy import insert, update

from core.dependencies import IdList
from core.response import SuccessResponse, ErrorResponse
from database.database import db_getter
from modules.admin.auth import dal, model, param, schema
from modules.auth import auth


router = APIRouter(
    prefix='/admin/auth/dept',
    tags = ['部门管理']
)

@router.get("/tree", summary="获取部门树")
async def get_depts_tree(
        params: param.DeptParams = Depends(),
        auth: auth.Auth = Depends(auth.FullAdminAuth(permissions=["auth.dept.list"]))
):
    datas = await dal.DeptDal(auth.db).get_tree_list(1, params)
    return SuccessResponse(datas, count=len(datas))

@router.post("/save", summary="保存部门信息")
async def create_dept(data: schema.Dept, auth: auth.Auth = Depends(auth.FullAdminAuth(permissions=["auth.dept.create", "auth.dept.update"]))):
    if data.id:
        return SuccessResponse(await dal.DeptDal(auth.db).put_data(data_id=data.id, data=data))
    else:
        return SuccessResponse(await dal.DeptDal(auth.db).create_data(data=data))

@router.delete("/delete", summary="批量删除部门", description="物理删除, 如果存在用户关联则无法删除")
async def delete_depts(ids: IdList = Depends(), auth: auth.Auth = Depends(auth.FullAdminAuth(permissions=["auth.dept.delete"]))):
    await dal.DeptDal(auth.db).delete_datas(ids.ids, v_soft=False)
    return SuccessResponse("删除成功")
